package com.sugon.controller.spare;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.consts.SparePartInoundResource;
import com.sugon.dao.SparePartInDao;
import com.sugon.entity.ErpSpTransactionEntity;
import com.sugon.entity.SparePartEntity;
import com.sugon.entity.SparePartInEntity;
import com.sugon.modules.base.consts.BusModule;
import com.sugon.modules.sparepart.model.vo.SparePartRequDetailVO;
import com.sugon.service.SparePartInService;
import com.sugon.service.SparePartRequDetailService;
import com.sugon.service.SparePartService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import com.sugon.utils.RRException;
import com.sugon.utils.excel.ExcelImport;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 入库记录Controller
 *
 * @author sugon
 * @date 2019-07-12 08:50:22
 */
@Controller
@RequestMapping("sparepartin")
public class SparePartInController {
    @Resource
    private SparePartInService sparePartInService;
    @Resource
    private SparePartRequDetailService sparePartRequDetailService;
    @Resource
    private SparePartService sparePartService;
    @Resource
    private SparePartInDao sparePartInDao;

    /**
     * 关联ERP入库记录
     *
     * @param id 入库记录ID
     * @return
     */
    @RequestMapping("/associateErpInboundRecord")
    @ResponseBody
    public R associateErpInboundRecord(@RequestParam String id, @RequestParam Long erpTransationId) {
        // 校验入库记录是否存在
        SparePartInEntity inboundRecord = sparePartInService.queryObject(id);
        if (inboundRecord == null) {
            return R.error("入库记录不存在！");
        }
        // 校验备件是否存在
        SparePartEntity sparePart = sparePartService.queryByCode(inboundRecord.getPartCode());
        if (sparePart == null) {
            return R.error("备件不存在，请确认！");
        }
        // 校验ERP入库记录是否存在
        ErpSpTransactionEntity erpSpTransactionRecord = sparePartInDao.queryByTransactionId(erpTransationId);
        if (erpSpTransactionRecord == null) {
            return R.error("ERP入库记录不存在！");
        }
        // 只有同一个备件才能进行关联
        if (!StrUtil.equals(sparePart.getErpCode(), erpSpTransactionRecord.getItemCode())) {
            return R.error("ERMS和ERP中入库的备件不是同一个备件，无法进行关联！");
        }
        inboundRecord.setErpInboundRecordId(erpTransationId);
        return sparePartInService.update(inboundRecord) > 0 ? R.ok() : R.error("关联ERP入库记录失败，请稍后重试！");
    }

    /**
     * 查看指定备件的ERP入库记录
     *
     * @param id 入库记录ID
     * @return
     */
    @RequestMapping("/listErpInboundRecord")
    @ResponseBody
    public R listErpInboundRecord(@RequestParam String id) {
        // 校验入库记录是否存在
        SparePartInEntity inboundRecord = sparePartInService.queryObject(id);
        if (inboundRecord == null) {
            return R.error("入库记录不存在！");
        }
        // 校验备件是否存在
        SparePartEntity sparePart = sparePartService.queryByCode(inboundRecord.getPartCode());
        if (sparePart == null) {
            return R.error("备件不存在，请确认！");
        }
        // 如果未配置ERP编码，则不允许查询
        if (StrUtil.isEmpty(sparePart.getErpCode())) {
            return R.error("尚未配置ERP编码，无法查看ERP入库记录！");
        }
        // 构建查询参数
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("itemCode", sparePart.getErpCode());
//        //  需要将已关联的ERP入库记录排除掉
//        List<SparePartInEntity> erpInboundRecords = sparePartInDao.listErpInboundRecord(sparePart.getPartCode());
//        if (CollectionUtil.isNotEmpty(erpInboundRecords)) {
//            params.put("excludedTransIdList", erpInboundRecords.stream().map(SparePartInEntity::getErpInboundRecordId).collect(Collectors.toList()));
//        }
        // 入库时间，一般晚于ERMS的入库时间
        params.put("startTime", DateUtil.formatDateTime(DateUtil.beginOfDay(inboundRecord.getInDate())));
        //查询列表数据
        Query query = new Query(params);
        List<ErpSpTransactionEntity> erpInboundList = sparePartInDao.queryErpInboundList(query);
        int total = sparePartInDao.queryErpInboundTotal(query);
        PageUtils pageUtil = new PageUtils(erpInboundList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("sparepartin:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {

        //查询列表数据
        Query query = new Query(params);

        List<SparePartInEntity> sparePartInList = sparePartInService.queryList(query);
        int total = sparePartInService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(sparePartInList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("sparepartin:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        SparePartInEntity sparePartIn = sparePartInService.queryObject(id);

        return R.ok().put("sparePartIn", sparePartIn);
    }

    /**
     * 保存
     */
    @AutoLog(value = "备件入库", busModule = BusModule.SPARE_PARTS)
    @RequestMapping("/save")
    @RequiresPermissions("sparepartin:save")
    @ResponseBody
    public R save(@RequestBody SparePartInEntity sparePartIn) {

        // 入库仓库必选
        if (StrUtil.isEmpty(sparePartIn.getInStoreId())) {
            return R.error("入库仓库必选！");
        }
        // 货位不能为空
        if (StrUtil.isAllEmpty(sparePartIn.getCargoLocation(), sparePartIn.getCargoLocationName())) {
            return R.error("货位不能为空！");
        }

        String msg = "入库成功！";
        // 如果是备件需求计划入库，那么入库来源必填
        if (SparePartInoundResource.BJXQ.getValue().equals(sparePartIn.getResources())) {
            // 需求计划明细ID必填
            String partNeedsItemId = sparePartIn.getPartNeedsItemId();
            if (StrUtil.isEmpty(partNeedsItemId)) {
                return R.error("入库来源为备件需求时，必须关联备件需求计划明细！");
            }
            // 校验备件需求计划明细ID是否有效
            SparePartRequDetailVO partRequDetailVO = sparePartRequDetailService.queryObject(partNeedsItemId);
            if (partRequDetailVO == null) {
                return R.error("无效备件需求计划ID，请确认！");
            }
            // 已取消在途的不允许重复入库
            boolean isCancelTransit = partRequDetailVO.getIsCancelTransit().equals(1);
            if (isCancelTransit) {
                return R.error("该需求计划明细已取消在途，不允许入库，请确认！");
            }
            // 本次入库数不得大于需求明细在途数
            if (sparePartIn.getInNum() > partRequDetailVO.getTransitNum()) {
                return R.error("该需求计划明细已取消在途，不允许入库，请确认！");
            }
            String remark = partRequDetailVO.getRemark();
            if (StrUtil.isNotEmpty(remark) && StrUtil.equalsAny(remark, "1", "0")) {
                msg = "入库成功，请告知备件管理员该备件已入库！";
            }
        }
        return sparePartInService.inbound(sparePartIn) > 0 ? R.ok(msg) : R.error("入库失败，请重试！");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sparepartin:update")
    @ResponseBody
    public R update(@RequestBody SparePartInEntity sparePartIn) {
        sparePartInService.update(sparePartIn);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sparepartin:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        sparePartInService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<SparePartInEntity> list = sparePartInService.queryList(params);

        return R.ok().put("list", list);
    }

    @RequestMapping("/import")
    @RequiresPermissions("sparepartin:import")
    @ResponseBody
    public R importE(@RequestParam("file") MultipartFile file) throws Exception {

        String err = "";
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        List list = ExcelImport.getExcelData(file);
        if (list != null && list.size() != 0) {
            String[] header = new String[]{"来源", "入库单号", "入库日期", "使用单位", "入库仓库", "货位", "系统编号", "名称", "规格", "单位", "单价",
                    "入库数量", "使用设备码", "使用设备", "使用工序", "操作人", "审核人", "审核状态", "审核时间", "备注", "添加时间"};
            /* , "入库日期", "使用单位", "入库仓库", "货位", "系统编号", "名称", "规格", "单位", "单价",
                    "入库数量", "使用设备码", "使用设备", "使用工序", "操作人", "审核人", "审核状态", "审核时间", "备注", "添加时间"*/
            String[] data = (String[]) list.get(0);
            int j = 0;
            for (String d : data) {
                if (header[j].equals(d.trim())) {
                    j++;
                }
            }
            if (j < header.length) {
                err = "找不到\"" + header[j] + "\"这一列";
            }
            if (err.equals("")) {
                /* deviceInfoService.delete(null);*/
                for (int i = 1; i < list.size(); i++) {
                    SparePartInEntity sparePartInEntity = new SparePartInEntity();
                    sparePartInEntity.setValues((String[]) list.get(i));
                    sparePartInService.save2(sparePartInEntity);
                }
            }
        }

        return R.ok().put("err", err);
    }

    @RequestMapping("/export")
    @RequiresPermissions("sparepartin:export")
    @ResponseBody
    public R export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        sparePartInService.export(params, response);
        return R.ok();
    }

}
